<template>
  <div class="head_search" >
    <div class="knife_container search_m">
      <router-link to="/" class="search_logo" ref="logo" :class="{'cursor_init': $route.name === 'Index'}"><img src="../images/knife_logo.png" alt=""></router-link>
      <PurchaseBox  ref="purchaseBox" v-if="!shopHide"></PurchaseBox>
      <div class="searchform" ref="searchform" :class="{'right': shopHide}">
        <div class="head-new-search-box">
          <el-select v-model="searchType" class="header-select">
            <el-option label="商品" :value="1"></el-option>
            <el-option label="规格" :value="2"></el-option>
          </el-select>
          <div class="head-new-search__input ">
            <input type="text"
            v-model.trim="keyword"
            :placeholder="placeholder"
            class="input-with-search"
            @focus="showRecordVisi"
            @blur="hiddenSearch"
            @keydown.13="goSearch"
            @input="searchEvent" />
            <i class="el-icon-search search_posi" @click="goSearch"></i>
          </div>
        </div>
        <div class="search-recommend" v-if="searchTips.length">
          <a v-for="(item, index) in searchTips" :key="index" class="keyword" @click="clickSearchRecord(item)">{{item}}</a>
        </div>
        <div class="search-popupmenu" v-if="recordVisi">
          <div class="search-popupmenu2-box">
            <div class="search-popupmenu2">
              <div class="popupmenu2-title">历史搜索<i class="el-icon-delete" @click="clearHistory"></i></div>
                <ul class="search-history">
                  <li v-for="(item, index) in storageList" :key="index" @click="clickSearchRecord(item)">{{item}}</li>
                </ul>
            </div>
          </div>
        </div>
        <!-- 搜索联想词 associationWords v-if="associationWords.length > 0 && associationWordsVisi" -->
        <div class="search-popupmenu" v-if="associationWords.length > 0 && associationWordsVisi">
          <ul>
            <li v-for="(item, index) in associationWords" :data-key="item" class="search-menuitem" :class="{'current': index === currentInd}"
            @mouseover="currentInd = index" @click="clickSearchRecord(item)">{{item}}
            </li>
          </ul>
        </div>
      </div>
    </div>
    <headMenu></headMenu>
  </div>
</template>
<script>
    import PurchaseBox from './PurchaseBox/PurchaseBox'
    import { mapActions, mapState } from 'vuex'
    import { Input, Button, Select, Option } from 'element-ui'
    import { getCookie, setSession, getSession, removeSession } from '@/config/mUntils'
    import { randomDigit, unique } from '@/tool/tool'
    import { findAssociationWord, getSearchTips } from '@/service/get-data'
    import headMenu from './headMenu.vue'
    export default {
      name: 'headSearch',
      components: {
        PurchaseBox,
        elInput: Input,
        elButton: Button,
        elSelect: Select,
        elOption: Option,
        headMenu
      },
      props: ['shopHide'],
      data () {
        return {
          keyword: '',
          currentInd: 0, // 当前的索引
          storageList: [],
          recordVisi: false,
          valueBefore: '', // 记录上一个搜索关键字
          associationWords: [], // 搜索联想词列表
          associationWordsVisi: false,
          searchTips: [], // 搜索推荐
          searchType: 1
        }
      },
      activated () {
      },
      computed: {
        ...mapState({
          cartList: state => {
            return state.shopcart.cartlist
          }
        }),
        routequery () {
          return this.$route.query
        },
        placeholder () {
          let key = this.$route.query.keyword || '按商品、品牌、型号进行搜索...'
          return key
        }
      },
      methods: {
        enter () {
          console.log('键盘')
        },
        // 鼠标离开搜索框
        hiddenSearch () {
          let timer = null
          this.currentInd = 0
          if (this.recordVisi || this.associationWordsVisi) {
            timer = setTimeout(() => {
              this.recordVisi = false
              this.associationWordsVisi = false
            }, 300)
          } else {
            clearTimeout(timer)
          }
        },
        async getKeywords () {
          let res = await getSearchTips()
          res = res.data
          if (res.resultCode && res.resultCode === 2000) {
            this.searchTips = res.data
          } else {
            this.$message({
              message: res.resultMsg,
              type: 'wraming'
            })
          }
        },
        // 清空历史记录
        clearHistory () {
          this.storageList = []
          removeSession('searchRecordList')
          this.recordVisi = false
        },
        // 获取焦点获取本地搜索记录
        showRecordVisi () {
          let list = []
          list = JSON.parse(getSession('searchRecordList'))
          if (list && list.length > 0) {
            this.storageList = list
            this.recordVisi = true
            this.associationWords = []
          } else {
            if (this.keyword === '') {
              this.recordVisi = true
              this.associationWords = []
            } else {
              this.recordVisi = false
            }
          }
        },
        ...mapActions(['fetchCartList']),
        // 去搜索
        goSearch () {
          this.keyword = this.keyword.replace(/(^\s*)|(select|update|create|drop)|(\s*$)/ig, '')
          // 没有输入搜索关键字 从导航上取
          this.keyword = this.keyword || this.routequery.keyword
          // 和上一个关键字相同 不触发
          if (this.searchType === this.$route.query.searchtype - 0 && this.valueBefore === this.keyword && this.$route.name === 'ModelList') return
          if (this.keyword) {
            this.valueBefore = this.keyword
            // 搜索关键字保存到list上 最长截取8
            let list = [...this.storageList]
            this.$store.commit('PREVIOUSKEY', list[0])
            this.storageList.unshift(this.keyword)
            this.storageList = this.storageList.slice(0, 8)
            this.storageList = unique(this.storageList)
            // 隐藏记录栏
            this.recordVisi = false
            this.associationWordsVisi = false
            setSession('searchRecordList', this.storageList)
            this.$router.push({name: 'ModelList', query: {searchtype: this.searchType, page: 1, keyword: this.keyword, r: randomDigit()}})
          } else {
            this.$message('请输入搜索关键字')
          }
        },
        // 搜索联想
        async searchEvent () {
          this.clearTimer()
          if (this.keyword && this.keyword.length > 0) {
            this.recordVisi = false
            this.associationWordsVisi = true
            this.searchTimer = setTimeout(() => {
              findAssociationWord(this.keyword).then(res => {
                this.associationWords = res.data.data
              }).catch(this.associationWords = [])
            }, 500)
          }
        },
        clearTimer () {
          if (this.searchTimer) {
            clearTimeout(this.searchTimer)
          }
        },
        // 初始化搜索关键字
        _initSearch () {
          if (this.routequery.keyword) {
            // ，,。？?！!˜~、\《》<>【】[]「」{}﹛﹜|
            this.keyword = this.routequery.keyword.replace(/[\uff0c|\u002c|\u3002|\uff1f|\u003f|\uff01|\u0021|\u02dc|\u007e|\u3001|\u005c|\u300a|\u300b|\u0026|\u003b|\u3010|\u3011|\u005b|\u005d|\u300c|\u300d|\u007b|\u007d|\ufe5b|\ufe5c|\u007c]/g, '')
          } else {
            this.keyword = ''
          }
        },
        // 是否含有Token
        hasToken () {
          let hastoken = getCookie('Token')
          if (hastoken) {
            this.fetchCartList()
            return true
          }
        },
        // 鼠标经过搜索记录
        mouseOverSearchRecord (ind, item) {
          this.currentInd = ind
        },
        // 点击搜索记录
        clickSearchRecord (item) {
          this.keyword = item
          this.goSearch()
          this.associationWords = []
        },
        // 删除
        deleteSearchRecord (index) {
          this.storageList.splice(this.currentInd, 1)
          setSession('searchRecordList', this.storageList)
        }
      },
      mounted () {
      },
      created () {
        this.hasToken()
        this._initSearch()
        this.getKeywords()
      },
      watch: {
        // 清除搜索条件
        '$route': function (to, from) {
          this.searchType = this.$route.query.searchtype ? this.$route.query.searchtype - 0 : false || 1
          let fromName = from.name
          let toName = to.name
          if (fromName === 'ProductList' && toName !== 'ProductList') {
            this.keyword = ''
          } else {
            this._initSearch()
          }
        },
        'keyword': {
          handler (val) {
            if (!val) return
            // ，,。？?！!˜~、\《》<>【】[]「」{}﹛﹜|
            this.keyword = val.replace(/[\uff0c|\u002c|\u3002|\uff1f|\u003f|\uff01|\u0021|\u02dc|\u007e|\u3001|\u005c|\u300a|\u300b|\u0026|\u003b|\u3010|\u3011|\u005b|\u005d|\u300c|\u300d|\u007b|\u007d|\ufe5b|\ufe5c|\u007c]/g, '')
          },
          deep: true
        }
      }
    }
</script>
<style lang="scss" scoped>
    $yellow_color:#FFCC00;
    $ora_color: #EF6600;
    $font_color:#474747;
    $height:50px;
    .cursor_init{
      cursor:initial;
    }
    .head_search{
      padding: 32.6px 0 0;
      background:#fff;
      min-width: 1200px;
      z-index: 999;
    }
    .search_m{
      background:#fff;
      height:60px;
      margin-bottom: 30px;
    }
    .search_logo{
      float: left;
      width: 204px;
      img{
          width: 100%;
      }
    }
    .searchform{
      position: relative;
      float: right;
      margin-top: 5px;
      width: 589px;
      }
      .right{
        float:right;
      }
      .search-recommend{
        margin-top: 8px;
        font-size: 12px;
        height: 12px;
        overflow: hidden;
        .keyword{
          padding-right: 7px;
          color: #B0B0B0;
        }
      }
      .yellow{
        color: $ora_color;
      }
      .search-popupmenu{
        position: absolute;
        user-select: none;
        left: 0;
        top: 50px;
        width: 588px;
        // height: auto;
        background: #fff;
        // border:1px solid #E5E5E5;
        cursor: pointer;
        margin: 0;
        -webkit-box-shadow: 1px 1px 3px #ededed;
        z-index: 99;
        .search-menuitem {
          width: 100%;
          color: #333333;
          font: 14px arial;
          line-height: 30px;
          padding-left: 20px;
          position: relative;
          cursor: pointer;
          box-sizing: border-box;
        }
        .current{
          background-color: #eee;
          .search_btn--delete{
            display: block;
          }
        }
        .search_btn--delete{
          display: none;
          color: #333;
          float: right;
          padding-right: 10px;
          &:hover{
            color: #1071a8
          }
        }
      }
      .search-popupmenu2-box{
        width: 100%;
        position: relative;
        .search-popupmenu2{
          width: 100%;
          height: 280px;
          box-sizing: border-box;
          padding: 22px 20px;
          border: 1px solid #E5E5E5;
          box-shadow: 1px 1px 3px #ededed;
          position: absolute;
          background-color: #fff;
          top: 0;
          overflow: hidden;
          .popupmenu2-title{
            color: #999999;
            overflow: hidden;
            i{
              float: right;
            }
          }
          .search-history{
            margin-top: 10px;
            height: 92%;
            li{
              height: 12.5%;
              font-size: 14px;
              line-height: 2;
              &:hover{
                background-color: #eee;
              }
            }
          }
          .popupmenu2-content{
            width: 50%;
            height: 100%;
            box-sizing: border-box;
            display: inline-block;
            float: left;
            &:nth-of-type(1){
              padding-right: 15px;
              border-right: 1px solid #f4f4f4;
            }
            &:nth-of-type(2){
              padding-left: 15px;
              border-left: 1px solid #f4f4f4;
            }
            .search-tips{
              margin-top: 10px;
              overflow: hidden;
              li{
                height: 24px;
                line-height: 24px;
                padding: 0 10px;
                font-size: 14px;
                margin: 0 10px 8px 0;
                border: 1.5px solid #FFCC00;
                color: #FFCC00;
                border-radius: 6px;
                display: inline-block;
                float: left;
              }
            }
          }
        }
      }
  .head-new-search-box{
    overflow: hidden;
    .header-select{
      float: left;
    }
    .head-new-search__input{
      position: relative;
      float: left;
      width: 485px;
      .input-with-search{
        position: relative;
        width: 91%;
        border: 1px solid #888;
        border-left: none;
        height: 45px;
        overflow: hidden;
        font-size: 12px;
        padding-left: 12px;
        box-sizing: border-box;
      }
      .search_posi{
        position: absolute;
        right: 0;
        top: 0;
        cursor: pointer;
        width: 50px;
        height: 100%;
        line-height: 45px;
        font-weight: 600;
        color: #666;
        font-size: 22px;
        text-align: center;
        background: #ffcc00;
        border-radius: 0 4px 4px 0;
      }
    }
  }
  
</style>
<style lang="scss">
.head-new-search-box{
  .header-select{
    .el-input__inner{
      border-radius: 4px 0 0 4px;
      font-size: 13px;
      width: 100px;
      height: 45px;
      padding-left: 30px;
      border: 1px solid #888;
    }
  }
}
  .searchform123{
    .el-input-group{
      overflow: hidden;
    }
    .el-input-group__prepend{
      width: 40px;
      border: 1px solid #888888;
      border-right: none;
      color: #555555;
    }
    .el-input-group__append{
      padding: 0 12px;
      background: #ffcc00;
      border: 1px solid #ffcc00;
      width: 50px;
      height: 44px;
      text-align: center;
      font-size: 23px;
      color: #666666;
      box-sizing: border-box;
    }
    .el-input__inner{
      border: 1px solid #888;
      border-right: none;
      height:45px;
    }
  }
  .header-prepend{
    .el-input__suffix .el-select__caret{
      color:#333333;
    }
    .el-input__inner{
      border:none;
    }
  }
  .popper__arrow{
    left: 100%!important;
  }
</style>

